package com.zzyl.service.impl;

import cn.hutool.crypto.digest.BCrypt;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.zzyl.base.PageResponse;
import com.zzyl.constant.SuperConstant;
import com.zzyl.dto.UserDto;
import com.zzyl.entity.User;
import com.zzyl.entity.UserRole;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.exception.EmailChangedException;
import com.zzyl.mapper.SysRoleMapper;
import com.zzyl.mapper.SysUserMapper;
import com.zzyl.mapper.SysUserRoleMapper;
import com.zzyl.service.SysUserService;
import com.zzyl.vo.UserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.RedirectView;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service
public class SysUserServiceimpl implements SysUserService {
    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysRoleServiceImpl sysRoleService;
    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;


    @Override
    public PageResponse<UserVo> getUserByPage(UserDto userDto, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        Page<UserVo> page = sysUserMapper.getUserByPage(userDto);
        List<UserVo> userVoList = page.getResult();
        userVoList.forEach(userVo -> {
            userVo.setRoleVoIds(sysUserMapper.findRoleIdsByUserId(userVo.getId()));
            userVo.setRoleLabels(sysUserMapper.findRoleLabelsByUserId(userVo.getId()));
        });
        PageResponse<UserVo> userVoPageResponse = PageResponse.of(page, UserVo.class);
        return userVoPageResponse;
    }

    @Override
    public Set<UserVo> getUserList(String realName) {
        return sysUserMapper.getUserList(realName);
    }

    @Override
    @Transactional
    public void createUser(UserDto userDto) {
        User user = new User();
        BeanUtils.copyProperties(userDto, user);
        String password = "888itcast.CN764%...";
        user.setPassword(BCrypt.hashpw(password,BCrypt.gensalt()));
        sysUserMapper.insertSelective(user);
        String DeptNo = user.getDeptNo();
        Integer count = sysUserMapper.selectParentDeptNo(DeptNo);
        if (count>0){
            throw new BaseException(BasicEnum.DEPT_BINDING_SELECT_USER);
        }
        List<UserRole> userRoles = Lists.newArrayList();
        userDto.getRoleVoIds().forEach(r -> {
            userRoles.add(UserRole.builder()
                    .userId(user.getId())
                    .roleId(Long.valueOf(r))
                    .dataState(SuperConstant.DATA_STATE_0)
                    .build());
        });
        sysUserRoleMapper.batchInsert(userRoles);

    }

    @Transactional
    @Override
    public void updateUser(UserDto userDto) {
        String oldEmail = sysUserMapper.selectByPrimaryKey(userDto.getId()).getEmail();

        User user = new User();
        BeanUtils.copyProperties(userDto, user);
        sysUserMapper.updateByPrimaryKeySelective(user);
        sysUserRoleMapper.deleteByPrimaryKey(user.getId());

        List<UserRole> userRoles = Lists.newArrayList();
        userDto.getRoleVoIds().forEach(r -> {
            userRoles.add(UserRole.builder()
                    .userId(user.getId())
                    .roleId(Long.valueOf(r))
                    .dataState(SuperConstant.DATA_STATE_0)
                    .build());
        });
        sysUserRoleMapper.batchInsert(userRoles);
        if (!oldEmail.equals(userDto.getEmail())){
            throw new BaseException(BasicEnum.USER_BINDING_SELECT_ROLE) ;
        }
    }

    @Override
    public void updateUserState(Long id, Integer status) {
        sysUserMapper.updateUserState(id, status);

    }

    @Transactional
    @Override
    public void deleteUser(Long[] userIds) {
        sysUserMapper.deleteUser(userIds);
        for (Long userId : userIds) {
            sysUserRoleMapper.deleteByUserId(userId);
        }
    }

    @Override
    public void resetPasswords(Long userId) {
        String password = "888itcast.CN764%...";
        password = BCrypt.hashpw(password, BCrypt.gensalt());
        sysUserMapper.resetPasswords(userId, password);
    }

//    @Override
//    public String getCurrentUser() {
//        return sysUserMapper.getCurrentUser();
//    }
}
